package com.health.healthSys.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.health.common.core.domain.entity.SysUser;
import com.health.common.utils.SecurityUtils;
import com.health.common.utils.StringUtils;
import com.health.system.service.ISysDeptService;
import com.health.system.service.ISysPostService;
import com.health.system.service.ISysRoleService;
import com.health.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.health.common.annotation.Log;
import com.health.common.core.controller.BaseController;
import com.health.common.core.domain.AjaxResult;
import com.health.common.enums.BusinessType;
import com.health.healthSys.domain.HealthUsers;
import com.health.healthSys.service.IHealthUsersService;
import com.health.common.utils.poi.ExcelUtil;
import com.health.common.core.page.TableDataInfo;

/**
 * 用户管理Controller
 *
 * @author maple
 * @date 2025-02-28
 */
@RestController
@RequestMapping("/healthSys/users")
public class HealthUsersController extends BaseController
{
    @Autowired
    private IHealthUsersService healthUsersService;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysUserService iSysUserService;
    /**
     * 查询用户管理列表
     */
    @PreAuthorize("@ss.hasPermi('healthSys:users:list')")
    @GetMapping("/list")
    public TableDataInfo list(HealthUsers healthUsers)
    {
        startPage();
        List<HealthUsers> list = healthUsersService.selectHealthUsersList(healthUsers);
        return getDataTable(list);
    }

    /**
     * 导出用户管理列表
     */
    @PreAuthorize("@ss.hasPermi('healthSys:users:export')")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HealthUsers healthUsers)
    {
        List<HealthUsers> list = healthUsersService.selectHealthUsersList(healthUsers);
        ExcelUtil<HealthUsers> util = new ExcelUtil<HealthUsers>(HealthUsers.class);
        util.exportExcel(response, list, "用户管理数据");
    }

    /**
     * 获取用户管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('healthSys:users:query')")
    @GetMapping(value = "/{userid}")
    public AjaxResult getInfo(@PathVariable("userid") Long userid)
    {
        return success(healthUsersService.selectHealthUsersByUserid(userid));
    }

    /**
     * 新增用户管理
     */
    @PreAuthorize("@ss.hasPermi('healthSys:users:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HealthUsers healthUsers)
    {
        SysUser user =new SysUser();
        Long[] longs = new Long[]{healthUsers.getRoleId()};
        user.setRoleIds(longs);
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        user.setNickName(healthUsers.getUsername());
        user.setUserName(healthUsers.getUsername());
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(healthUsers.getPasswordHash()));
        user.setStatus(healthUsers.getUserStatus());
        user.setEmail(healthUsers.getEmail());
        user.setAvatar(healthUsers.getHeadImg());
        user.setPhonenumber(healthUsers.getPhone());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        userService.insertUser(user);
        healthUsers.setSysUserId(user.getUserId());
        return toAjax(healthUsersService.insertHealthUsers(healthUsers));
    }

    /**
     * 修改用户管理
     */
    @PreAuthorize("@ss.hasPermi('healthSys:users:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HealthUsers healthUsers)
    {
        SysUser user =new SysUser();
        Long[] longs = new Long[]{healthUsers.getRoleId()};
        user.setRoleIds(longs);
        user.setNickName(healthUsers.getUsername());
        user.setUserName(healthUsers.getUsername());
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(healthUsers.getPasswordHash()));
        user.setStatus(healthUsers.getUserStatus());
        user.setEmail(healthUsers.getEmail());
        user.setAvatar(healthUsers.getHeadImg());
        user.setPhonenumber(healthUsers.getPhone());
        user.setUserId(healthUsers.getSysUserId());
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        user.setUpdateBy(getUsername());
        userService.updateUser(user);
        return toAjax(healthUsersService.updateHealthUsers(healthUsers));
    }

    /**
     * 删除用户管理
     */
    @PreAuthorize("@ss.hasPermi('healthSys:users:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userids}")
    public AjaxResult remove(@PathVariable Long[] userids) throws InterruptedException {
        // 查询一下用户管理中的对应数据
        List<Long> sysUserIdList = new ArrayList<>();
        for (Long userid : userids) {
            HealthUsers healthUsers = healthUsersService.selectHealthUsersByUserid(userid);
            if (healthUsers == null) {
                return error("用户不存在");
            }
            if (healthUsers.getSysUserId() != null) {
                sysUserIdList.add(healthUsers.getSysUserId());
            }
        }
        Long[] sysUserids = sysUserIdList.toArray(new Long[0]);
        if (ArrayUtils.contains(sysUserids, getUserId()))
        {
            return error("当前用户不能删除");
        }
        if(sysUserids.length>0){
            userService.deleteUserByIds(sysUserids);
        }
        return toAjax(healthUsersService.deleteHealthUsersByUserids(userids));
    }

    @GetMapping("/getUserIdByUsername")
    public AjaxResult getUserIdByUsername(@RequestParam String username) {
        SysUser user = iSysUserService.selectUserByUserName(username);
        return user != null ? AjaxResult.success(user.getUserId()) : AjaxResult.error("用户不存在");
    }
}
